#pragma once 
#include <queue>
#include <thread>
#include <unordered_map>

#include "Msg.h"
#include "LuaAPI.h"
#include "ConnWriter.h"

using namespace std;

extern "C" {
    #include "lua.h"
    #include "lualib.h"
    #include "lauxlib.h"
}

class Service {
private:
    lua_State* luaState;
public:
    Service();
    ~Service();

    void PushMsg(shared_ptr<BaseMsg> msg); // 插入消息
    bool ProcessMsg();  // 执行消息
    void ProcessMsgs(int max); 

private:
    shared_ptr<BaseMsg> PopMsg(); // 取出消息

public: // 回调函数
    void OnInit(); // 服务创建后
    void OnMsg(shared_ptr<BaseMsg> msg); // 服务收到消息后
    void OnExit(); // 服务退出后

private:
    void OnServiceMsg(shared_ptr<ServiceMsg> serviceMsg); // 服务间消息
    void OnAcceptMsg(shared_ptr<SocketAcceptMsg> socketAcceptMsg); // 有新连接
    void OnRWMsg(shared_ptr<SocketRWMsg> socketRWMsg); // clientfd消息，下述三个分支
    void OnSocketData(int fd, const char* buff, int len); // 收到数据
    void OnSocketWritable(int fd); // 可写
    void OnSocketClose(int fd); // 连接关闭

public:
    uint32_t id;  // 唯一ID
    shared_ptr<string> type; // 类型
    bool isExiting = false;  // 正在退出

public:
    queue<shared_ptr<BaseMsg>> msgQueue;
    pthread_spinlock_t queueLock;

// ------------------ in global queue ---------------- //
public:
    bool inGlobal = false;
    pthread_spinlock_t inGlobalLock;
    void SetInGlobal(bool isIn); 

    // ---------------- connwriter -------------------- //
public:
    unordered_map<uint32_t, shared_ptr<ConnWriter>> writers;
};